
import 'package:bookshelf/entity/book_entity.dart';
import 'package:bookshelf/http/api.dart';
import 'package:bookshelf/page/book_page.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import '../http/api_url.dart';
import '../main.dart';
import '../widget/app_bar.dart';
import '../util/timer_manager.dart';

class RankDetail extends StatefulWidget {
  const RankDetail({Key? key}) : super(key: key);

  @override
  State<RankDetail> createState() => _RankDetailState();
}

class _RankDetailState extends State<RankDetail> {

  final RxList<BookEntity> _list = RxList();

  String? id ='';
  String? title ='';
  String? from;

  var page = 1;

  @override
  initState() {
    super.initState();

    var (id,title,from) = Get.arguments;
    this.id = id;
    this.title = title;
    this.from = from;

    WidgetsBinding.instance.addPostFrameCallback((_){
      timer.startCountDown(CountDownMode.action, (){
        timer.cancel();
        Get.until((route) => route.isFirst);
      });
    });

    initData();
  }

  initData() {
    findList(id).then((value){
      if(value != null){
        _list.addAll(value);
      }
    });
  }


  _title(){
    return Container(
      width: double.infinity,
      margin: EdgeInsets.only(top: 10.h,left: 8.w,right: 8.w),
      child: Stack(
        alignment: AlignmentDirectional.centerStart,
        children: [
          InkWell(
            onTap: (){
              if(from != null){
                timer.cancel();
              }
              Get.back();
            },
            child: Image.asset("assets/images/back.png",width:50.w,fit: BoxFit.fitWidth,)
          ),
          Align(child: SizedBox(width:300.w,child: Text('--《$title》--',style: TextStyle(color: Colors.white,fontSize: 10.sp),textAlign: TextAlign.center,),),),
          Positioned(right:0,child: Obx(() => Text("${timer.actionTime.value}",style: TextStyle(color: Colors.white,fontSize: 8.sp),)))
        ],
      )
    );
  }



  _itemBuilder(index){
    var item = _list[index];
    RxBool showAnimation = false.obs;
    RxInt recommendCount = (item.recommend_score??0).obs;
    return InkWell(
      onTap: (){
        Get.to(()=>const Book(),arguments: item);
      },
      child: Container(
          margin: EdgeInsets.only(top: 5.r,left: 8.r,right: 8.r),
          padding: EdgeInsets.only(top: 5.r,bottom:5.r,left: 8.r,right: 8.r),
          // alignment: Alignment.center,
          // height: 110.h,
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(Radius.circular(4.r)),
          ),
          child: Stack(
            children: [
              Positioned(child: Image.network('${item.cover}',width: 67.w,height:90.h,fit: BoxFit.fill,
                errorBuilder: ( BuildContext context, Object error, StackTrace? stackTrace,){
                  return  Image.asset('assets/images/default.png',width: 67.w,height:90.h,fit: BoxFit.fill);
                },),),
              Positioned(left:80.w,top:8.h,right:50.w,
                  child: SingleChildScrollView(
                    scrollDirection: Axis.horizontal,
                    child: Text('《${item.title}》',maxLines:1,style: TextStyle(color: Colors.black,fontSize: 10.sp,fontWeight: FontWeight.bold),),
                  )
              ),
              if(item.place != null && item.place!.isNotEmpty)...[
                Positioned(right:12.w,top:8.h,child: Image.asset("assets/images/there.png",width: 30.w,fit: BoxFit.fitWidth)),
              ],
              Positioned(left:80.w,top:22.h,child: Text('${item.author}',style: TextStyle(color: Colors.black,fontSize: 8.sp),),),
              Positioned(left:80.w,top:38.h,child: InkWell(
                onTap: (){
                  resort.addByNo(item.no);
                  recommendCount.value = recommendCount.value +1;
                  item.recommend_score = recommendCount.value;
                  if(!showAnimation.value){
                    showAnimation.value = true;
                    Future.delayed(const Duration(milliseconds: 300),(){
                      showAnimation.value = false;
                    });
                  }
                },
                child: Image.asset("assets/images/like_click.png",width: 40.w,fit: BoxFit.fitWidth)
              )),
              Positioned(left:90.w,top:8.h,child: Obx(() => InkWell(
                onTap: (){
                  resort.addByNo(item.no);
                  recommendCount.value = recommendCount.value +1;
                  item.recommend_score = recommendCount.value;
                  if(!showAnimation.value){
                    showAnimation.value = true;
                    Future.delayed(const Duration(milliseconds: 300),(){
                      showAnimation.value = false;
                    });
                  }
                },
                child: Visibility(visible:showAnimation.value,child: Image.asset("assets/images/star.gif",width: 40.w,fit: BoxFit.fitWidth)))),
              ),
              Positioned(left:116.w,top:33.h,child: Container(
                width: 10.w,
                height: 10.w,
                alignment: Alignment.center,
                decoration:  BoxDecoration(
                    borderRadius: BorderRadius.all(Radius.circular(44.r)),
                    color: const Color.fromRGBO(255, 0, 0, 1)
                ),
                child: Obx(() => Text('${recommendCount.value>999?'999+':recommendCount.value}',style: TextStyle(color: Colors.white, fontSize: 4.sp),)),
              )),
              Positioned(left:80.w,top:55.h,child: Text('位置：${_analyzePlace(item.place)}',style: TextStyle(color: Colors.black,fontSize: 8.sp),),),
              Positioned(left:80.w,top:70.h,child: Text('索书号：${item.search_no}  条码：${item.no}',style: TextStyle(color: Colors.black,fontSize: 8.sp),),),
            ],
          )
      ),
    );
  }

  _analyzePlace(String? place){
    if(place == null || place.isEmpty){
      return '';
    }
    String room = place.substring(0,2);
    String column = place.substring(2,6);
    String side = place.substring(6,8);
    String knot = place.substring(8,10);
    String floor = place.substring(10,12);
    return '$room区$column列${side=='01'?'A面':'B面'}$knot节$floor层';
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          image: DecorationImage(
            fit: BoxFit.fill,
            image: AssetImage(
              "assets/images/rank_bg.png",
            ),
          ),
        ),
        child: Column(
          children: [
            appBar(bg: 'rank_top_bg'),
            _title(),
           Obx(() => Expanded(child: ListView.builder(
             itemBuilder: (context, index) {
               return _itemBuilder(index);
             },
             itemCount: _list.length,
           ),))
          ],
        ),
      ),
    );
  }
}

